package com.ruoyi.web.controller.system;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;

import com.github.pagehelper.PageHelper;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.system.domain.Cash;
import com.ruoyi.system.service.ICashService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.Integral;
import com.ruoyi.system.domain.Member;
import com.ruoyi.system.service.IIntegralService;
import com.ruoyi.system.service.IMemberService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.domain.Ztree;

/**
 * 业务员Controller
 * 
 * @author ruoyi
 * @date 2019-10-14
 */
@Controller
@RequestMapping("/system/member")
public class MemberController extends BaseController
{
    private String prefix = "system/member";

    @Autowired
    private IMemberService memberService;
    @Autowired
    private IIntegralService integralService;
    @Autowired
    private ICashService cashService;

    @RequiresPermissions("system:member:view")
    @GetMapping()
    public String member()
    {
        return prefix + "/member";
    }

    /**
     * 查询业务员树列表
     */
    @RequiresPermissions("system:member:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(Member member)
    {
        startPage();
        List<Member> list = memberService.selectMemberList(member);
        return getDataTable(list);
    }

    /**
     * 导出业务员列表
     */
    @RequiresPermissions("system:member:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(Member member)
    {
        PageHelper.startPage(1, 99999999, "create_time desc");
        List<Member> list = memberService.selectMemberList(member);
        for(Member mem:list){
            if(mem.getPid()!=null && !mem.getPid().toString().equals("")){
                Member pmember = memberService.selectMemberById(mem.getPid());
                if(pmember!=null){
                    mem.setParentMemberName(pmember.getNickName());
                }
            }
        }
        ExcelUtil<Member> util = new ExcelUtil<Member>(Member.class);
        return util.exportExcel(list, "member");
    }

    /**
     * 下级用户
     */
    @GetMapping(value = "/getEcharts/{id}")
    public String getEcharts(@PathVariable(value = "id", required = true) Long id, ModelMap mmap)
    {
        mmap.put("member", memberService.selectMemberById(id));
        return prefix + "/echarts";
    }
    /**
     * 加载业务员echarts
     */
    @GetMapping("/echartsData/{id}")
    @ResponseBody
    public HashMap<String, Object> echartsData(@PathVariable(value = "id", required = true) Long id)
    {
        HashMap<String, Object> data = new HashMap<String, Object>();
        Member member = memberService.selectMemberById(id);
        List<HashMap<String, Object>> listdata = new ArrayList<HashMap<String, Object>>();
        List<HashMap<String, Object>> linksdata = new ArrayList<HashMap<String, Object>>();
        List<HashMap<String, Object>> categories = new ArrayList<HashMap<String, Object>>();

        if(member.getPid()!=null&&!member.getPid().toString().equals("")){
            Member memberParent = memberService.selectMemberById(member.getPid());
            if(memberParent!=null){
                HashMap<String, Object> listdataMap = new HashMap<String, Object>();
                listdataMap.put("id",memberParent.getId());
                listdataMap.put("name",memberParent.getNickName());
                listdataMap.put("realName",memberParent.getRealName());
                listdataMap.put("category","0级");
                listdataMap.put("symbolSize",45);
                listdata.add(listdataMap);
                HashMap<String, Object> linksdataMap = new HashMap<String, Object>();
                linksdataMap.put("source",memberParent.getId()+"");
                linksdataMap.put("target",member.getId()+"");
                linksdataMap.put("sourceName",memberParent.getNickName());
                linksdataMap.put("targetName",member.getNickName());
                linksdata.add(linksdataMap);
                HashMap<String, Object> categoriesMap = new HashMap<String, Object>();
                categoriesMap.put("name","0级");
                categories.add(categoriesMap);
            }

        }

        HashMap<String, Object> listdataMap = new HashMap<String, Object>();
        listdataMap.put("id",member.getId());
        listdataMap.put("name",member.getNickName());
        listdataMap.put("realName",member.getRealName());
        listdataMap.put("category","1级");
        listdataMap.put("symbolSize",60);
        listdata.add(listdataMap);

        HashSet<Integer> set = new HashSet<Integer>();
        set.add(1);
        getMemberChilds(1, member.getId(), listdata, linksdata,set);
        for(Integer n:set){
            HashMap<String, Object> categoriesMap = new HashMap<String, Object>();
            categoriesMap.put("name",n+"级");
            categories.add(categoriesMap);
        }
        data.put("listdata",listdata);
        data.put("linksdata",linksdata);
        data.put("categories",categories);
        return data;
    }
    public void getMemberChilds(int num,long id,List<HashMap<String, Object>> listdata,List<HashMap<String, Object>> linksdata, HashSet<Integer> set) {
        Member membero = new Member();
        membero.setPid(id);
        List<Member> members = memberService.selectMemberList(membero);
        int n = 0;
        if(members.size()>0){
            n = num+1;
            set.add(n);
            for(Member member:members){
                HashMap<String, Object> listdataMap = new HashMap<String, Object>();
                listdataMap.put("id",member.getId());
                listdataMap.put("name",member.getNickName());
                listdataMap.put("realName",member.getRealName());
                listdataMap.put("category",n+"级");
                listdataMap.put("symbolSize",33);
                listdata.add(listdataMap);
                HashMap<String, Object> linksdataMap = new HashMap<String, Object>();
                linksdataMap.put("source",id+"");
                linksdataMap.put("target",member.getId()+"");
                linksdataMap.put("sourceName",memberService.selectMemberById(id).getNickName());
                linksdataMap.put("targetName",member.getNickName());
                linksdata.add(linksdataMap);
                getMemberChilds(n,member.getId(),listdata,linksdata,set);
            }
        }

    }

    /**
     * 新增业务员
     */
    @GetMapping("/add")
    public String add(){ return prefix + "/add"; }

    /**
     * 新增保存业务员
     */
    @RequiresPermissions("system:member:add")
    @Log(title = "业务员", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(Member member)
    {
        return toAjax(memberService.insertMember(member));
    }

    /**
     * 修改业务员
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        Member member = memberService.selectMemberById(id);
        mmap.put("member", member);
        return prefix + "/edit";
    }

    /**
     * 修改保存业务员
     */
    @RequiresPermissions("system:member:edit")
    @Log(title = "业务员", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(Member member)
    {
        return toAjax(memberService.updateMember(member));
    }

    /**
     * 删除
     */
    @RequiresPermissions("system:member:remove")
    @Log(title = "业务员", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        String[] idArr = ids.split(",");
        for(String id:idArr){
            Integral integral = new Integral();
            integral.setMemberId(Long.parseLong(id));
            List<Integral> selectIntegralList = integralService.selectIntegralList(integral);
            for(Integral integ:selectIntegralList){
                integralService.deleteIntegralById(integ.getId());
            }
            Cash cash = new Cash();
            cash.setMemberId(Long.parseLong(id));
            List<Cash> selectCashList = cashService.selectCashList(cash);
            for(Cash ca:selectCashList){
                cashService.deleteCashById(ca.getId());
            }
        }
        return toAjax(memberService.deleteMemberByIds(ids));
    }

    /**
     * 选择业务员树
     */
    @GetMapping(value = { "/selectMemberTree/{id}", "/selectMemberTree/" })
    public String selectMemberTree(@PathVariable(value = "id", required = false) Long id, ModelMap mmap)
    {
        if (StringUtils.isNotNull(id))
        {
            mmap.put("member", memberService.selectMemberById(id));
        }
        return prefix + "/tree";
    }

    /**
     * 加载业务员树列表
     */
    @GetMapping("/treeData")
    @ResponseBody
    public List<Ztree> treeData()
    {
        List<Ztree> ztrees = memberService.selectMemberTree();
        return ztrees;
    }

    /**
     * 地址
     */
    @GetMapping("/address/{id}")
    public String address(@PathVariable("id") Long id, ModelMap mmap)
    {
        Member member = memberService.selectMemberById(id);
        mmap.put("member", member);
        return "system/address/address";
    }

    /**
     * 积分记录
     */
    @GetMapping("/integralRecord/{id}")
    public String integralRecord(@PathVariable("id") Long id, ModelMap mmap)
    {
        Member member = memberService.selectMemberById(id);
        mmap.put("member", member);
        return "system/integral/integral";
    }
}
